#!/usr/bin/env python
# coding: utf-8

# In[1]:


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import pymysql
import warnings
warnings.filterwarnings('ignore')
plt.rcParams['font.family']='SimHei'
plt.rcParams['axes.unicode_minus']= False


# $n_A=(\sigma_A^2+\sigma_B^2 /k)(\frac{z_{1-\alpha}~~~ +  z_{1-\beta}~~~}{\mu_{A} - \mu_{B}})^2$

# In[2]:


#读取Excel数据
df=pd.read_excel(
    './ab_data.xlsx',
    sheet_name=0, # 读取哪⼀个Excel中⼯作表，默认第⼀个
    header = 0 # 使⽤第⼀⾏数据作为列索引
    )
df
df.head()


# control:对照组，treatment:实验组，new_page:B banner，old_page:A banner

# 设置:$\alpha = 0.05, \beta = 0.2 ,K_{12}=n_2/n_1、K_{ab}=n_b/n_a $

# In[5]:


alpha = 0.05
beta = 0.2
k12 = 147276/147202
kab = 145311/1965
print(k12,kab)


# 求$z_{1-\alpha}和z_{1-\beta}$

# In[6]:


z_alpha = stats.norm.ppf(1-alpha)
z_beta = stats.norm.ppf(1-beta)
print(z_alpha,z_beta)


# # 计算一类指标

# ## 求对照组的平均点击率及标准差 $\mu_1 、\sigma_1$

# In[7]:


df_control = df.loc[df.group=='control',['user_id','timestamp','group','landing_page','converted']]
df_control


# In[8]:


miu_1 = df_control.converted.mean()
sigema_1 = df_control.converted.std()
sigema_x = df_control.converted.var()
pr = "miu_1 = {0}\nsigema_1 = {1}".format(miu_1,sigema_1)
print(pr)


# ## 求实验组的平均点击率及标准差 $\mu_2 、\sigma_2$

# In[9]:


df_treatment = df.loc[df.group=='treatment',['user_id','timestamp','group','landing_page','converted']]
df_treatment


# In[10]:


miu_2 = df_treatment.converted.mean()
sigema_2  = df_treatment.converted.std()
pr = "miu_2 = {0}\nsigema_2 = {1}".format(miu_2,sigema_2)
print(pr)


# ## 计算$(\sigma_{1}^2+\sigma_{2}^2 /k_{12})、{\mu_{1} - \mu_{2}}$

# In[11]:


temp_a = sigema_1**2+(sigema_2**2/k12)
temp_b = np.power(2*sigema_1,2)
# temp_b = miu_1-miu_2
# print("temp_a=%0.8f,temp_b=%0.8f" % (temp_a,temp_b))
pr = "temp_a={0}\ntemp_b={1}".format(temp_a,temp_b)
print(pr)


# ## 求样本量：$n_a、n_b$

# In[12]:


n_1 = (z_alpha+z_beta) ** 2
n_1 = temp_a * n_1
n_1 = n_1/temp_b
n_2 = n_1*k12
pr = "n_1 = {0}\nn_2 = {1}".format(n_1,n_2)
print(pr)
# n_1,n_2


# ## 计算统计量的P值

# 求：$\bar{x} - \mu$

# In[59]:


dif_12 = miu_2-miu_1
dif_12


# 求：$\frac{\sigma_2^2}{n_2} + \frac{\sigma_1^2}{n_1}$

# In[14]:


varsum_12 = (sigema_2**2 / df_treatment.converted.count()) + (sigema_1**2 / df_control.converted.count())
varsum_12,df_treatment.converted.count(),df_control.converted.count()


# In[15]:


P_12 = stats.norm.cdf(dif_12,loc = (sigema_1*2),scale = np.sqrt(varsum_12))
P_12


# $P_{12}$小于0.05，可拒绝H0，即可认为：实验组平均点击量 – 对照组平均点击量 < 两个标准差

# # 计算 二类 指标

# ## 计算实验组中新（B）旧（A）两个版本的均值和标准差

# In[17]:


df_treatment_a = df_treatment.loc[df.landing_page=='old_page',['user_id','timestamp','group','landing_page','converted']]
df_treatment_a


# In[18]:


df_treatment_b = df_treatment.loc[df.landing_page=='new_page',['user_id','timestamp','group','landing_page','converted']]
df_treatment_b


# In[19]:


miu_a = df_treatment_a.converted.mean()
sigema_a  = df_treatment_a.converted.std()
miu_b = df_treatment_b.converted.mean()
sigema_b  = df_treatment_b.converted.std()
pr = "miu_a = {0}  sigema_a = {1}\nmiu_b = {2}  sigema_b = {3}".format(miu_a,sigema_a,miu_b,sigema_b)
print(pr)


# ## 计算样本量

# 计算$(\sigma_{b}^2+\sigma_{a}^2 /k_{ab})、{\mu_{b} - \mu_{a}}$

# In[72]:


temp_a = sigema_b**2+(sigema_a**2/kab)
temp_b = np.power(2*sigema_2,2)
# temp_b = miu_b-miu_1
pr = "temp_a={0}\ntemp_b={1}".format(temp_a,temp_b)
print(pr)


# In[73]:


n_a = (z_alpha+z_beta) ** 2
n_a = temp_a * n_a
n_a = n_a/temp_b
n_b = n_a*kab
pr = "n_a = {0}\nn_b = {1}".format(n_a,n_b)
print(pr)
# n_1,n_2


# ## 计算统计量的P值

# 求：$\bar{x} - \mu$

# In[74]:


dif_ab = miu_b-miu_a
dif_ab


# 求：$\frac{\sigma_b^2}{n_b} + \frac{\sigma_a^2}{n_a}$

# In[128]:


varsum_ab = (sigema_b**2 / df_treatment_b.converted.count()) + (sigema_a**2 / df_treatment_a.converted.count())
varsum_ab


# In[76]:


P_ab = stats.norm.cdf(dif_ab,loc = (sigema_a*2),scale = np.sqrt(varsum_ab))
P_ab


# $P_{ab}$小于0.05，可拒绝H0，即可认为：实验组B banner的平均点击率与A banner的平均点击率之差 > 两个标准差

# # 把步骤2-4封装成函数

# In[81]:


def P_Alpha_Comparison(alpha,mu_e,s_e,n_e,mu_c,s_c,n_c): # alpha、实验组（均值、标准差、样本量）、对照组（均值、标准差、样本量）
    dif_mu = mu_e - mu_c
    varsum_ec = (s_e**2 / n_e) + (s_c**2 / n_c)
    P_ec = stats.norm.cdf(dif_mu,loc = (s_c*2),scale = np.sqrt(varsum_ec))
    Z = dif_mu / np.sqrt(varsum_ec)
    pr = "P_ec = {0}\nZ = {1}".format(P_ec,Z)
#     pr = "P_ec = {0}\nZ = {1}\nvarsum_ec = {2}\ndif = {3}".format(P_ec,Z,varsum_ec,dif_mu)
    print(pr)
    if P_ec < alpha:
        print("拒绝原假设 H0！")
    else:
        print("无法拒绝原假设 H0！")


# In[82]:


P_Alpha_Comparison(0.05,
                   miu_2,sigema_2,df_treatment.converted.count(),
                   miu_1,sigema_1,df_control.converted.count())


# In[83]:


P_Alpha_Comparison(0.05,
                   miu_b,sigema_b,df_treatment_b.converted.count(),
                   miu_a,sigema_a,df_treatment_a.converted.count())


# In[ ]:




